package com.phone.utils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tisen on 2017/7/6.
 */
public class MessageUtil {


    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {

        Map<String, String> map = new HashMap<>();
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();

        List<Element> elements = root.elements();

        for (Element e :
                elements) {
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        inputStream = null;
        return map;
    }

    public static String parseXml(String xmlString) throws Exception {
        System.out.println(xmlString);
        Document document = DocumentHelper.parseText(xmlString);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        Element element = elements.get(0);
        String status = element.elementText("status");
        System.out.println("status = "+status);
        return status;
    }

    public static void main(String args[]) {
        try {
            System.out.print(MessageUtil.parseXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><sms><mt><status>10</status><msgid>1dc093e1296e4951b5aea70424711122</msgid></mt></sms>"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
